﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Simple.Common.Data;
using Simple.Entity;
using Simple.EF;
using Simple.Common.EasyUICommon;
using Simple.Common.Core.Pager;
using Simple.ViewModel;
using Simple.Common.Pager;
using Simple.Common.Core.Log;
using System.Web.Mvc;
using System.Data.Entity;
using EntityFramework.Extensions;
using Simple.Entity.Models;
using Simple.Common.Core.Tools;
using Simple.Common.Core.Encryption;

namespace Simple.Service
{
    public class UserService : ApplicationService
    {
        private readonly WorkEfRepository<Sys_User> _userRepository;
        private readonly WorkEfRepository<Sys_Role> _roleRepository;
        private readonly WorkEfRepository<Sys_UserForMenu> _userForMenuRepository;
        private readonly WorkEfRepository<Sys_Menu> _menuRepository;
        private const string _removeMenu = "#"; //JsTree会有一个#的根节点 需要去除

        public UserService(WorkEfRepository<Sys_User> userRepository, WorkEfRepository<Sys_Role> roleRepository, WorkEfRepository<Sys_UserForMenu> userForMenuRepository, WorkEfRepository<Sys_Menu> menuRepository)
        {
            _userRepository = userRepository;
            _roleRepository = roleRepository;
            _userForMenuRepository = userForMenuRepository;
            _menuRepository = menuRepository;
        }

        public Sys_User FindById(long id)
        {
            return _userRepository.Find(id);
        }

        public bool IsRepeatLoginNo(string loginNo)
        {
            return _userRepository.TableNoTracking.Count(m => m.LoginNo == loginNo) == 0;
        }

        public IPagedList<UserListModel> GetUsers(SimpleMvcPage page, UserQueryModel queryModel)
        {
            var query = from a in _userRepository.TableNoTracking
                        join b in _roleRepository.TableNoTracking
                        on a.RoleId equals b.Id into ab
                        from c in ab.DefaultIfEmpty()
                        select new UserListModel
                        {
                            Id = a.Id,
                            ShortName = a.ShortName,
                            LoginNo = a.LoginNo,
                            IsActive = a.IsActive,
                            Contact = a.Contact,
                            CreateTime = a.CreateTime,
                            RoleId = a.RoleId,
                            RoleName = c.RoleName
                        };
            if (queryModel != null)
            {
                if (!string.IsNullOrEmpty(queryModel.LoginNo))
                {
                    query = query.Where(m => m.LoginNo.Contains(queryModel.LoginNo));
                }

                if (queryModel.RoleId != null)
                {
                    query = query.Where(m => m.RoleId == queryModel.RoleId);
                }

                if (queryModel.StartTime != null)
                {
                    query = query.Where(m => DbFunctions.DiffDays(m.CreateTime, queryModel.StartTime) <= 0);
                }

                if (queryModel.EndTime != null)
                {
                    query = query.Where(m => DbFunctions.DiffDays(m.CreateTime, queryModel.EndTime) >= 0);
                }
            }

            var users = query.ToPagedList(page);
            return users;


        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="sys_User"></param>
        /// <returns></returns>
        public SimpleResult Add(Sys_User sys_User)
        {
            int count = _userRepository.TableNoTracking.Count(m => m.LoginNo == sys_User.LoginNo);
            if (count > 0)
            {
                return GetError("已经存在相同的登录账号");
            }
            sys_User.PassWordSalt = RandomHelper.GetRandom().ToString();
            sys_User.PassWord = SimpleMD5Helper.GetMD5(sys_User.PassWord + sys_User.PassWordSalt);
            int ret = _userRepository.Add(sys_User);
            return GetResult(ret);
        }

        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="Sys_User"></param>
        /// <returns></returns>
        public SimpleResult Update(Sys_User Sys_User)
        {
            int ret = _userRepository.Update(Sys_User);
            return GetResult(ret);
        }

        /// <summary>
        /// 删除用户(软删除)
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public SimpleResult Delete(long userId)
        {
            var delUser = _userRepository.Find(userId);
            if (delUser == null)
            {
                return GetError();
            }
            int ret = _userRepository.Delete(delUser);
            return GetResult(ret);
        }

        /// <summary>
        /// 获取用户权限树
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public List<MenuTreeListModel> GetMenuTree(long userId)
        {
            List<string> menuIdList = _userForMenuRepository.TableNoTracking.Where(m => m.UserId == userId).Select(m => m.MenuId.ToString()).ToList();
            List<MenuTreeListModel> model = _menuRepository.TableNoTracking.OrderBy(m => m.ParentId).ThenBy(m => m.Sort).Select(a => new MenuTreeListModel
            {
                id = a.Id.ToString(),
                icon = a.Icon,
                sort = a.Sort,
                text = a.MenuName,
                state = new StateClass { opened = false },
                parent = a.ParentId.ToString()
            }).ToList();
            List<MenuTreeListModel> reModel = new List<MenuTreeListModel>();

            foreach (var item in model)
            {
                item.children = model.Where(m => m.parent == item.id).ToList();
                if (item.parent == "0")
                {
                    item.state.opened = true;
                    reModel.Add(item);
                }
            }

            foreach (var item in model)
            {
                if (item.children == null || item.children.Count == 0)
                {
                    item.state.selected = menuIdList.Count(m => m == item.id) > 0;
                }
            }

            return reModel;
        }

        /// <summary>
        /// 编辑用户权限
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="menuIdList"></param>
        /// <returns></returns>
        public SimpleResult DistributionAction(long userId, string menuIdList)
        {
            var ret = _userForMenuRepository.Table.Where(m => m.UserId == userId).Delete();
            if (!string.IsNullOrEmpty(menuIdList))
            {
                List<Sys_UserForMenu> userForMenuList = new List<Sys_UserForMenu>();
                foreach (var menuId in menuIdList.Split(',').Distinct())
                {
                    if (menuId == _removeMenu) continue;
                    userForMenuList.Add(new Sys_UserForMenu()
                    {
                        UserId = userId,
                        MenuId = long.Parse(menuId)
                    });
                }
                ret = _userForMenuRepository.AddRange(userForMenuList);
            }

            return GetResult(ret);
        }


    }
}
